package com.demo.listener;


import com.demo.callback.CallBackDev2_4g;
import com.demo.callback.CallBackSockets;
import com.demo.common.SocketConnectStatus;
import com.demo.common.TCPSocketConnect;
import com.demo.service.EquipmentDataService;
import com.rfid.bean.Reader2_4g;
import com.rfid.uhf.service.Reader2_4gService;
import com.rfid.uhf.service.impl.Reader2_4gServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * 监听模式
 */
@Slf4j
@Component
public class TCPSocketConnectListener implements CallBackSockets {

    @Autowired
    private EquipmentDataService equipmentDataService;

    private Thread threadHeartbeat;
    public static List<Reader2_4g> list = new ArrayList<>();
    public Reader2_4gService service = new Reader2_4gServiceImpl();

    @Value("${server.port}")
    private int port;


//    @PostConstruct
    public void init(){
        TCPSocketConnect connect = new TCPSocketConnect();
        connect.startServer(port,new TCPSocketConnectListener());
        log.info("服务监听已启动");
        while(true);//阻塞，让程序一直运行
        //connect.stopServer();
    }

    @Override
    public void result(Socket socket, String IP, int port) {
        log.info("TCP Sever 连接");
        Reader2_4g reader = service.tcpServerConnect(socket, new CallBackDev2_4g(equipmentDataService));
        service.beginInv(reader);
        //service.stopInv(reader);
        log.info("连接设备对象:"+reader.toString());
        list.add(reader);//对象添加到集合中
        threadHeartbeat = new Thread(new SocketConnectStatus(socket,IP));//心跳
        threadHeartbeat.start();
    }
}
